package com.peking.donations.base.security;

import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Pattern;

public class CsrfRequestMatcher implements RequestMatcher {
	private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

	@Override
	public boolean matches(HttpServletRequest request) {
		if (!CollectionUtils.isEmpty(execludeUrls)) {
			String servletPath = request.getServletPath();
			for (String url : execludeUrls) {
				// 此处是contains判断，后期可改进为pattern
				if (servletPath.contains(url)) {
					return false;
				}
			}
		}

		return !allowedMethods.matcher(request.getMethod()).matches();
	}

	private List<String> execludeUrls;

	public List<String> getExecludeUrls() {
		return execludeUrls;
	}

	public void setExecludeUrls(List<String> execludeUrls) {
		this.execludeUrls = execludeUrls;
	}

}